- pointers contain memory address of variable. Note that we can not use simply int, float, double data types to store the address, as address require different kind of data to store.
Note:
General rule is "use reference in c++ over pointers, use pointers only if you have to". Pointers are avoided unless they are necessary.
Recap:
- variables are declared with : int x=5; float y=5.0;
Have a look at Data modifiers to know more.
- Declaration of pointer: int * p = &x; here p is pointer variable which will store the address of variable 'x' where as the '* p' contains the value stored in varialbe 'x'(this is called as dereferencing)
- So 'p' is integer pointer, '* p' is integer.
- We define the pointer using '* ' and dereference using the same '* ' but these don't have same meaning.
-
The reason we want to use pionters:
- If we need multiple variables (x and * p) to talk about same area of memory, this is commonly used for functions for passing data.
- In this way we can allow change of value a variable holds by using pointers in functions and changing value of the * p , which will reflect outside the function as well.
#include <iostream> #include <stdio.h> int main(int argc, char *argv[]) { int a=5; int b=10; int c=a+b; int * d=&a; int * e=&b; std::cout<<"the values of a and b are "<<a<<"\t"<<b<<std::endl; std::cout<<"the address of a and b are "<<&a<<"\t"<<&b<<std::endl; std::cout<<"the address of a and b are "<<d<<"\t"<<e<<std::endl; std::cout<<"the value of a and b are "<<*&a<<"\t"<<*&b<<std::endl; std::cout<<"the value of a and b are "<<*d<<"\t"<<*e<<std::endl; return 0; }
Output
the values of a and b are 5 10
the address of a and b are 0x7ff7b09ba3cc 0x7ff7b09ba3c8
the address of a and b are 0x7ff7b09ba3cc 0x7ff7b09ba3c8
the value of a and b are 5 10
the value of a and b are 5 10
#include<iostream> void fun(int *p) { *p=20; } int main() { int x=30; int *y=&x; //here y is pointer variable which will store address of variable 'x' fun(y); std::cout<<x; //it will print 20 , since the value at address is changed in function, it can be useful. return 0; }